package com.websocketOfNotice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.websocketOfNotice.msgDomain.SendMessage;
import living.com.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lizijian
 */

@Component
@Slf4j
public class WebSocket {
  private static final ObjectMapper objectMapper=new ObjectMapper();
  private static final RestTemplate rest=new RestTemplate();
  public static boolean sendMessage(int toUserId, SendMessage<?> sendMessage){
    Session session = getSessionByUserId(toUserId);
    if(session==null){
      return false;
    }
    try{
      session.getBasicRemote()
          .sendText(objectMapper.writeValueAsString(sendMessage));
    }catch (IOException e){
      log.error("消息发送失败");
      log.error(e.getMessage());
      return false;
    }
    return true;
  }

  private static Session getSessionByUserId(int userId){
    Session session = doGetSessionByUserId(userId);
    if(session!=null){
      log.info(userId+"号用户在线");
      return session;
    }
    log.info(userId+"号用户不在线");
    return null;
  }

  private static Session doGetSessionByUserId(int userId) {
    try {
      ApiResult<Session> result = rest.getForObject("http://localhost:20000/livingAndHelping/userIsOnLine", ApiResult.class, userId);
      log.info("获取用户是否在线的结果为: {}",result);
      return result.getData();
    } catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
}
